<template>
  <div class="app-container">
    <div class="custom_card_0" v-show="showSearch">
      <el-form
        :model="queryParams"
        ref="queryForm"
        :inline="true"
        label-width="110px"
      >
        <el-form-item label="保险公司名" prop="companyName">
          <el-input
            v-model="queryParams.companyName"
            placeholder="请输入保险公司名"
            clearable
            size="small"
            @keyup.enter.native="handleQuery"
          />
        </el-form-item>
        <el-form-item label="适用保险类型" prop="type">
          <el-select
            v-model="queryParams.type"
            placeholder="请选择适用保险类型"
          >
            <template v-for="item in dict.type.company_type">
              <el-option
                :label="item.label"
                :value="item.value"
                :key="item.value"
              ></el-option>
            </template>
          </el-select>
        </el-form-item>
        <el-form-item label="是否启用" prop="isAvailable">
          <el-select
            v-model="queryParams.isAvailable"
            placeholder="是否启用"
            clearable
            @1change="handleQuery"
          >
            <template v-for="item in dict.type.company_isAvailable">
              <el-option
                :label="item.label"
                :value="item.value"
                :key="item.value"
              ></el-option>
            </template>
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button
            type="primary"
            icon="el-icon-search"
            size="mini"
            @click="handleQuery"
            >搜索</el-button
          >
          <el-button icon="el-icon-refresh" size="mini" @click="resetQuery"
            >重置</el-button
          >
        </el-form-item>
      </el-form>
    </div>
    <div class="custom_card">
      <el-row :gutter="10" class="mb10">
        <el-col :span="1.5">
          <el-button
            type="primary"
            plain
            icon="el-icon-plus"
            size="mini"
            @click="handleAdd"
            v-hasPermi="['maintenance:company:add']"
            >新增</el-button
          >
        </el-col>
        <el-col :span="1.5">
          <el-button
            type="warning"
            plain
            icon="el-icon-download"
            size="mini"
            :loading="exportLoading"
            @click="handleExport"
            v-hasPermi="['maintenance:company:export']"
            >导出</el-button
          >
        </el-col>
        <right-toolbar
          :showSearch.sync="showSearch"
          @queryTable="getList"
        ></right-toolbar>
      </el-row>

      <el-table
        v-loading="loading"
        :data="companyList"
        @selection-change="handleSelectionChange"
        border
      >
        <el-table-column
          label="保险公司名"
          align="center"
          prop="companyName"
          min-width="140"
          show-overflow-tooltip
        />
        <el-table-column
          label="省名"
          align="center"
          prop="provinceName"
          min-width="120"
          show-overflow-tooltip
        />
        <el-table-column
          label="市名称"
          align="center"
          prop="cityName"
          min-width="120"
          show-overflow-tooltip
        />
        <el-table-column
          label="区/县名称"
          align="center"
          prop="areaName"
          min-width="120"
          show-overflow-tooltip
        />
        <el-table-column
          label="详细地址"
          align="center"
          prop="addrDetail"
          min-width="160"
          show-overflow-tooltip
        />
        <el-table-column
          label="联系电话"
          align="center"
          prop="phone"
          min-width="140"
          show-overflow-tooltip
        />
        <el-table-column
          label="适用保险类型"
          align="center"
          prop="type"
          min-width="100"
          show-overflow-tooltip
        ></el-table-column>
        <el-table-column
          label="是否启用"
          align="center"
          prop="isAvailable"
          min-width="100"
          show-overflow-tooltip
        >
          <template slot-scope="scope">
            <dict-tag
              :options="dict.type.sys_available"
              :value="scope.row.isAvailable"
            />
          </template>
        </el-table-column>
        <el-table-column
          label="所属租户"
          align="center"
          prop="tenantName"
          min-width="200"
          show-overflow-tooltip
        />
        <el-table-column
          label="操作"
          align="center"
          class-name="small-padding fixed-width"
          fixed="left"
          width="200"
        >
          <template slot-scope="scope">
            <el-button
              size="mini"
              type="text"
              @click="handleUpdate(scope.row)"
              v-if="scope.row.isAvailable == 0"
              v-hasPermi="['maintenance:company:edit']"
              >修改</el-button
            >
            <el-button
              size="mini"
              type="text"
              @click="handleDelete(scope.row)"
              v-if="scope.row.isAvailable == 0"
              v-hasPermi="['maintenance:company:remove']"
              >删除</el-button
            >
            <el-button
              size="mini"
              type="text"
              @click="handleAvailable(scope.row, 1)"
              v-if="scope.row.isAvailable == 0"
              >启用</el-button
            >
            <el-button
              size="mini"
              type="text"
              @click="handleAvailable(scope.row, 0)"
              v-if="scope.row.isAvailable == 1"
              >停用</el-button
            >
          </template>
        </el-table-column>
      </el-table>

      <pagination
        v-show="total > 0"
        :total="total"
        :page.sync="queryParams.pageNum"
        :limit.sync="queryParams.pageSize"
        @pagination="getList"
      />
    </div>
    <!-- 添加或修改保险公司对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="800px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="110px">
        <el-form-item label="保险公司名" prop="companyName">
          <el-input v-model="form.companyName" placeholder="请输入保险公司名" />
        </el-form-item>
        <!-- <el-form-item label="分公司名" prop="branchName">
                    <el-input v-model="form.branchName" placeholder="请输入分公司名" />
                </el-form-item> -->
        <el-form-item label="地址" prop="areaName">
          <el-cascader
            clearable
            size="large"
            ref="myCascader"
            :options="options"
            v-model="selectedOptions"
            placeholder="请选择省/市/区"
            @change="handleChange"
          ></el-cascader>
        </el-form-item>
        <el-form-item label="详细地址" prop="addrDetail">
          <el-input
            v-model="form.addrDetail"
            type="textarea"
            placeholder="请输入内容"
          />
        </el-form-item>
        <el-form-item label="联系电话" prop="phone">
          <el-input v-model="form.phone" placeholder="请输入联系电话" />
        </el-form-item>
        <el-form-item label="保险类型" required>
          <el-checkbox-group v-model="checkList">
            <template v-for="item in dict.type.company_type">
              <el-checkbox
                :label="String(item.value)"
                :key="String(item.value)"
                >{{ item.label }}</el-checkbox
              >
            </template>
          </el-checkbox-group>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  stopUsingEnabled,
  listCompany,
  getCompany,
  delCompany,
  addCompany,
  updateCompany,
  exportCompany,
} from '@/api/maintenance/company'
import {
  listStore,
  getStore,
  delStore,
  addStore,
  updateStore,
  exportStore,
  editAvailable,
  getAllStore,
  getCityCode,
} from '@/api/store/store'
import { regionData, CodeToText } from 'element-china-area-data' // 引入三级联动

export default {
  name: 'Company',
  dicts: ['company_type', 'company_isAvailable', 'sys_available'],
  data() {
    return {
      // 遮罩层
      loading: true,
      // 导出遮罩层
      exportLoading: false,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 保险公司表格数据
      companyList: [],
      // 弹出层标题
      title: '',
      // 选择地区数据
      options: [], //regionData省市区数据
      selectedOptions: [],
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        companyNo: null,
        companyName: null,
        branchName: null,
        provinceId: null,
        provinceName: null,
        cityId: null,
        cityName: null,
        areaId: null,
        areaName: null,
        addrDetail: null,
        phone: null,
        type: null,
        isAvailable: null,
        deptId: null,
        tenantId: null,
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        companyName: [{ required: true, message: '保险公司名不能为空' }],
        branchName: [{ required: true, message: '分公司名不能为空' }],
        areaName: [{ required: true, message: '地址不能为空' }],
        addrDetail: [{ required: true, message: '详细地址不能为空' }],
        phone: [{ required: true, message: '联系电话不能为空' }],
        type: [{ required: true, message: '保险类型不能为空' }],
      },
      checkList: [],
      selection: [],
    }
  },
  created() {
    this.getList()
    this.getCityCode()
  },
  methods: {
    emitData() {
      return this.selection[0]
    },
    getCityCode() {
      getCityCode().then((res) => {
        let provinceIds = res.data.provinceIds
        let cityIds = res.data.cityIds
        let arr = []

        for (let var1 of regionData) {
          if (provinceIds.indexOf(var1.value) != -1) {
            let children = []
            for (let var2 of var1.children) {
              if (cityIds.indexOf(var2.value) != -1) {
                children.push(var2)
              }
            }
            let province = {
              label: var1.label,
              value: var1.value,
              children: children,
            }
            arr.push(province)
          }
        }
        this.options = arr
        console.log(this.options)
      })
    },
    /** 查询保险公司列表 */
    getList() {
      this.loading = true
      listCompany(this.queryParams).then((response) => {
        this.companyList = response.rows
        this.total = response.total
        this.loading = false
      })
    },
    // 取消按钮
    cancel() {
      this.open = false
      this.reset()
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        companyNo: null,
        companyName: null,
        branchName: null,
        provinceId: null,
        provinceName: null,
        cityId: null,
        cityName: null,
        areaId: null,
        areaName: null,
        addrDetail: null,
        phone: null,
        type: null,
        delFlag: null,
        isAvailable: null,
        createBy: null,
        createTime: null,
        updateBy: null,
        updateTime: null,
        remark: null,
        deptId: null,
        tenantId: null,
      }
      this.resetForm('form')
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1
      this.getList()
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm('queryForm')
      this.handleQuery()
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map((item) => item.companyNo)
      this.single = selection.length !== 1
      this.multiple = !selection.length
      this.selection = selection
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.checkList = []
      this.selectedOptions = []
      this.reset()
      this.open = true
      this.title = '添加保险公司'
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset()
      console.log(row)
      const id = row.companyNo || this.ids
      getCompany(id).then((response) => {
        this.form = response.data
        this.open = true
        this.title = '修改保险公司'
        this.selectedOptions = [
          response.data.provinceId,
          response.data.cityId,
          response.data.areaId,
        ]
        this.checkList = String(response.data.type).split(',')
      })
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs['form'].validate((valid) => {
        if (valid) {
          this.form.type = String(this.checkList)
          if (this.form.companyNo != null) {
            updateCompany(this.form).then((response) => {
              this.$modal.msgSuccess('修改成功')
              this.open = false
              this.getList()
            })
          } else {
            addCompany(this.form).then((response) => {
              this.$modal.msgSuccess('新增成功')
              this.open = false
              this.getList()
            })
          }
        }
      })
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.companyNo || this.ids
      this.$modal
        .confirm('是否确认删除数据项？')
        .then(function () {
          return delCompany(ids)
        })
        .then(() => {
          this.getList()
          this.$modal.msgSuccess('删除成功')
        })
        .catch(() => {})
    },
    /** 启停用 */
    handleAvailable(row, isAvailable) {
      stopUsingEnabled({
        isAvailable: isAvailable,
        companyNo: row.companyNo,
      }).then((res) => {
        this.getList()
        this.$modal.msgSuccess(res.msg)
      })
    },
    /** 导出按钮操作 */
    handleExport() {
      const queryParams = this.queryParams
      this.$modal
        .confirm('是否确认导出所有保险公司数据项？')
        .then(() => {
          this.exportLoading = true
          return exportCompany(queryParams)
        })
        .then((response) => {
          this.$download.name(response.msg)
          this.exportLoading = false
        })
        .catch(() => {})
    },
    // 省市区三级
    handleChange(value) {
      var nodes = this.$refs['myCascader'].getCheckedNodes()
      if (nodes && nodes[0]) {
        var node = nodes[0]
        this.form.provinceId = node.parent.parent.value
        this.form.provinceName = node.parent.parent.label
        this.form.cityId = node.parent.value
        this.form.cityName = node.parent.label
        if ('市辖区' == node.parent.label) {
          this.form.cityName = node.parent.parent.label
        } else {
          this.form.cityName = node.parent.label
        }
        this.form.areaId = node.value
        this.form.areaName = node.label
      } else {
        this.form.provinceId = null
        this.form.provinceName = null
        this.form.cityId = null
        this.form.cityName = null
        this.form.areaId = null
        this.form.areaName = null
      }
    },
  },
}
</script>
